let pagenum = 1
let pagesize = 10;
const getgames = async() => {
    let keyword = document.querySelector('.search').value
    let keyurl;
    if (keyword && keyword) {
        keyurl = `getgames?pagenum=${pagenum}&pagesize=${pagesize}&keyword=${keyword}`;
    } else {
        keyurl = `getgames?pagenum=${pagenum}&pagesize=${pagesize}`;
    }
    let response = await ajax(keyurl)
    let tbody = document.querySelector('tbody');
    let games = response.data
    let total = response.total
    let page_num = Math.floor(total % pagesize == 0 ? total / pagesize : total / pagesize + 1)
    init_page(page_num)
    const userregtime = time => time.split('T')[0]
    tbody.innerHTML = ''
    for (const game of games) {
        let tr = document.createElement('tr');
        tr.innerHTML = `
                        <td>${game.id}</td>
                        <td>
                            <div class="img">
                                <img src="${game.cover}" alt="">
                            </div>
                        </td>
                        <td>${game.gamename}</td>
                        <td>${game.copyright_name}</td>
                        <td>${game.typename}</td>
                        <td>${userregtime(game.publishdate)}</td>
                        <td>${game.system==0?'手游':'端游'}</td>
                        <td>
                            <button class="update" onclick="updategame(${game.id})">编辑</button>
                            <button class="deletebutton" onclick="delete_game(${game.id})">删除</button>
                        </td>
                        `
        tbody.appendChild(tr)
    }
}

const updategame = _uid => {
    location.href = `./game_update.html?uid=${_uid}`
}

const deletegame = (uid) => {
    let response = ajax(`deletegame?id=${uid}`, 'DELETE')
    location.href = './games.html'
    alert('删除游戏成功')
}

const init_page = page_num => {
    let page_ul = document.querySelector('.page_ul')
    page_ul.innerHTML = ''
    for (let i = 1; i <= page_num; i++) {
        let li = document.createElement('li')
        li.innerHTML = i
        if (i == pagenum) {
            li.className = 'pagenumactive'
        }
        li.addEventListener('click', function() {
            pagenum = parseInt(li.innerHTML)
            getgames()
        })
        page_ul.appendChild(li)
    }
}

window.onload = function() {
    getgames()
}